package com.green.voluntaryfiling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.green.voluntaryfiling.common.DataGridView;
import com.green.voluntaryfiling.domain.UniversityInfo;
import com.green.voluntaryfiling.domain.UniversityScoreBySchoolAll;
import com.green.voluntaryfiling.mapper.UniversityInfoMapper;
import com.green.voluntaryfiling.mapper.UniversityScoreBySchoolAllMapper;
import com.green.voluntaryfiling.mapper.UniversityScoreBySchoolMapper;
import com.green.voluntaryfiling.service.UniversityInfoService;
import com.green.voluntaryfiling.util.HistoryFormatSchoolMatchingRateUtil;
import com.green.voluntaryfiling.util.PhysicsFormatSchoolMatchingRateUtil;
import com.green.voluntaryfiling.vo.MatchInfoVo;
import com.green.voluntaryfiling.vo.SchoolDetailRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

//import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

/**
 * Created with IntelliJ IDEA.
 * @Author: Green
 * @Date: 2022/03/18/0:15
 * @Description: 
 */


@Service
public class UniversityInfoServiceImpl extends ServiceImpl<UniversityInfoMapper, UniversityInfo> implements UniversityInfoService{

    @Autowired
    private UniversityInfoMapper universityInfoMapper;

    @Autowired
    private UniversityScoreBySchoolAllMapper universityScoreBySchoolAllMapper;

    @Autowired
    private UniversityScoreBySchoolMapper universityScoreBySchoolMapper;


    //分值权重
    private Double authority_score = 30.0;

    /**
     * 查询全部学校信息
     * @return
     */
    @Override
    public DataGridView queryAllUniversityInfo(int page1,int limit) {
        IPage<UniversityInfo> page = new Page<>(page1,limit);
        QueryWrapper<UniversityInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("id");
        page = this.universityInfoMapper.selectPage(page,queryWrapper);
//        System.out.println(page.getTotal());
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    /**
     * 查询模糊学校匹配信息
     * @param schoolname
     * @return
     */
    @Override
    public DataGridView queryLikeUniversityInfo(String schoolname,int page1,int limit) {
        IPage<UniversityInfo> page = new Page<>(page1,limit);
        QueryWrapper<UniversityInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(schoolname),"university_name",schoolname);
        queryWrapper.orderByAsc("id");
        this.universityInfoMapper.selectPage(page,queryWrapper);

        return new DataGridView(page.getTotal(),page.getRecords());
    }


    /**
     * 学校优先匹配
     * @param matchInfoVo
     * @return
     */
    @Override
    public DataGridView matchSchoolWithSearchingSchoolFirst(MatchInfoVo matchInfoVo) {
        Integer counter = 0,countSize = 0;   //计数器
        List<UniversityInfo> lists = new ArrayList<>() ;    //声明查询lists
        List<UniversityInfo> r = new ArrayList<UniversityInfo>();
        List<UniversityInfo> temp = new ArrayList<UniversityInfo>();
        List<List<UniversityInfo>> list = new ArrayList();      //镶套List
        //获取大于学生分数的学校总录取人数
        int allMoreThanStScoreAccpected = 0;


        if (!matchInfoVo.getProviceValue().equalsIgnoreCase("全国")) {
            //对应地区和学科的匹配查询
            lists = this.universityInfoMapper.getUniversityByProvinceAndSubjectForMatch(matchInfoVo.getProviceValue(),matchInfoVo.getSubject());
        }else {
            //匹配学科全部学校查询
            lists = this.universityInfoMapper.getUniversityByAllrangeAndSubjectForMatch(matchInfoVo.getSubject());
        }

        for (UniversityInfo record : lists) {
            //符合预测条件上下30分 此处改为上30分 下25分
            if((matchInfoVo.getSt_score()+30.0 > record.getScore()+0.0)
                    &&(matchInfoVo.getSt_score()-25.0 < record.getScore())){

                /*
                    预测 此处加下当学生为理科，则调用PhysicsSchoolMatchingUtil的方法；
                    当学生为文科科，则调用HistorySchoolMatchingUtil的方法；

                    根据学校表中accpeted_num数量后，当学生为理科，则调用PhysicsSchoolMatchingAcceptedUtil的方法；
                    当学生为文科科，则调用HistorySchoolMatchingAcceptedUtil的方法；该方法最后一个形参为学校录取人数
                    目前下面的情况为学生为理科，且不包含录取人数为参数。
                */
                if (matchInfoVo.getSubject().equalsIgnoreCase("理科")){

                    /*
                        根据3+6+1（分数+专业+人数）理科预测
                        record.setPrediction(PhysicsSchoolMatchingAcceptedUtil.percent(record.getRanking(),matchInfoVo.getSt_ranking(),
                                Double.valueOf(record.getScore()),matchInfoVo.getSt_score(),record.getAcceptedNum()));
                    */


                    /*根据预测指数理科预测 求大于学生分数的学校录取总人数
                    MySQL查询优化*/
                    Integer universityScoreMoreThanStudent = universityInfoMapper.selectByKobetsuAndScore(matchInfoVo.getSubject(), (int) Math.round(record.getScore()));

                    allMoreThanStScoreAccpected=universityScoreMoreThanStudent;

                    /*
                        根据预测指数理科预测 设置概率
                        record.setPrediction(PhysicsSchoolAcceptanceRateUtil.percent((double)matchInfoVo.getSt_ranking().intValue(),matchInfoVo.getSt_score(),allMoreThanStScoreAccpected));
                    */

                    //根据（分数+专业+人数）+预测指数 综合的正式录取概率理科预测
                    record.setPrediction(PhysicsFormatSchoolMatchingRateUtil.percent((double)matchInfoVo.getSt_ranking().intValue(),matchInfoVo.getSt_score(),allMoreThanStScoreAccpected,
                            record.getRanking(), Double.valueOf(record.getScore()),record.getAcceptedNum()));
                    allMoreThanStScoreAccpected =0;//清0
                }else {

                    /*
                        根据3+6+1（分数+专业+人数）文科预测
                        record.setPrediction(HistorySchoolMatchingAcceptedUtil.percent(record.getRanking(),matchInfoVo.getSt_ranking(),
                                Double.valueOf(record.getScore()),matchInfoVo.getSt_score(),record.getAcceptedNum()));
                    */

                    /*根据预测指数文科预测 求大于学生分数的学校录取总人数
                    MySQL查询优化*/
                    Integer universityScoreMoreThanStudent = universityInfoMapper.selectByKobetsuAndScore(matchInfoVo.getSubject(), (int) Math.round(record.getScore()));

                    allMoreThanStScoreAccpected=universityScoreMoreThanStudent;

                    /*
                        根据预测指数文科预测 设置概率
                        record.setPrediction(HistorySchoolAcceptanceRateUtil.percent((double)matchInfoVo.getSt_ranking().intValue(),matchInfoVo.getSt_score(),allMoreThanStScoreAccpected));
                    */

                    //根据（分数+专业+人数）+预测指数 综合的正式录取概率文科预测
                    record.setPrediction(HistoryFormatSchoolMatchingRateUtil.percent((double)matchInfoVo.getSt_ranking().intValue(),matchInfoVo.getSt_score(),allMoreThanStScoreAccpected
                            ,record.getRanking(), Double.valueOf(record.getScore()),record.getAcceptedNum()));
                    allMoreThanStScoreAccpected = 0;//清0
                }

                /*
                record.setPrediction(PhysicsSchoolMatchingUtil.percent(record.getRanking(),matchInfoVo.getSt_ranking(),
                        Double.valueOf(record.getScore()),matchInfoVo.getSt_score()));
                */

                //计数器
                countSize ++ ;

                /*
                * 添加至r列表
                *
                * */
                r.add(record);

            }
        }
        Collections.sort(r, new Comparator<UniversityInfo>() {          //排列函数 DESC
            @Override
            public int compare(UniversityInfo o1, UniversityInfo o2) {
                if (o1.getPrediction().equals(o2.getPrediction())){
                    return 0;
                }
                return o1.getPrediction()-o2.getPrediction()>0?1:-1;
            }
        });

        /*
        * 处理排序后数组
        * */
        for (UniversityInfo universityInfo : r) {
            temp.add(universityInfo);
            counter ++ ;
            if (counter.equals(matchInfoVo.getLimit())){
                //只当满添加
                list.add(temp);
                temp = new ArrayList<>();
                counter = 0 ;
            }
        }
        if (!temp.isEmpty()){
            //判断最后一次是否还有数据
            list.add(temp);
        }

        return new DataGridView(Long.valueOf(countSize),list);
    }



    /**
     * 查询学校信息(超详细)
     * @param university_name
     * @param subject
     * @return
     */
    @Override
    public DataGridView querySchoolDetail(String university_name, String subject) {
        try{
            SchoolDetailRes schoolDetailRes = this.universityInfoMapper.getUniversityDetail(university_name,subject);
            schoolDetailRes.setSubject(subject);
            //增加学校往年分数和排位  MySQL优化
            UniversityScoreBySchoolAll universityScoreBySchoolAlls_2016 = universityScoreBySchoolAllMapper.selectByUniversityNameAndKobetsuAndEnrolledYear(university_name, subject, 2016);
            UniversityScoreBySchoolAll universityScoreBySchoolAlls_2017 = universityScoreBySchoolAllMapper.selectByUniversityNameAndKobetsuAndEnrolledYear(university_name, subject, 2017);
            UniversityScoreBySchoolAll universityScoreBySchoolAlls_2018 = universityScoreBySchoolAllMapper.selectByUniversityNameAndKobetsuAndEnrolledYear(university_name, subject, 2018);
            UniversityScoreBySchoolAll universityScoreBySchoolAlls_2019 = universityScoreBySchoolAllMapper.selectByUniversityNameAndKobetsuAndEnrolledYear(university_name, subject, 2019);
            schoolDetailRes.setSchoolLowestRanking_2019(universityScoreBySchoolAlls_2019.getSchoolLowestRanking());
            schoolDetailRes.setSchoolLowestScore_2019(universityScoreBySchoolAlls_2019.getSchoolLowestScore());
            schoolDetailRes.setSchoolLowestRanking_2018(universityScoreBySchoolAlls_2018.getSchoolLowestRanking());
            schoolDetailRes.setSchoolLowestScore_2018(universityScoreBySchoolAlls_2018.getSchoolLowestScore());
            schoolDetailRes.setSchoolLowestRanking_2017(universityScoreBySchoolAlls_2017.getSchoolLowestRanking());
            schoolDetailRes.setSchoolLowestScore_2017(universityScoreBySchoolAlls_2017.getSchoolLowestScore());
            schoolDetailRes.setSchoolLowestRanking_2016(universityScoreBySchoolAlls_2016.getSchoolLowestRanking());
            schoolDetailRes.setSchoolLowestScore_2016(universityScoreBySchoolAlls_2016.getSchoolLowestScore());
            return new DataGridView(Long.valueOf(1),schoolDetailRes);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }



}
